package com.glut.forum.config;

import com.glut.forum.common.annotations.CurrentUserInfo;
import com.glut.forum.common.beans.UserInfo;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author milo
 * @since 2021/9/5 下午3:04
 * @version 1.0
 */
public class CurrentUserIdHandlerMethodArgResolver implements HandlerMethodArgumentResolver {

    /**
    * 判断是否支持使用@CurrentUserId注解的参数
    */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果该参数注解有@CurrentUser且参数类型是UserInfo
        return methodParameter.getParameterAnnotation(CurrentUserInfo.class) != null &&methodParameter.getParameterType() == UserInfo.class;
    }

    /**
    * 注入参数值
    */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //取得HttpServletRequest
        HttpServletRequest request= (HttpServletRequest) nativeWebRequest.getNativeRequest();
        //取出UserID
        UserInfo userInfo = new UserInfo();

        userInfo.setItemId(Integer.valueOf(request.getAttribute("uid").toString()));

        userInfo.setItemCode(request.getAttribute("ucode").toString());

        return userInfo;
    }
}